home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Komputer 2010 April
/
PCWorld0410.iso
/
pluginy Firefox
/
54809
/
54809.xpi
/
chrome
/
dictCheck-0.0.6.005.jar
/
content
/
iframeInfoDialog.js
< prev
next >
Wrap
Text File
|
2010-02-14
|
27KB
|
739 lines
// encoding='UTF-8'
/*
# Autor : Krzysztof Slawinski
# Description : window for displaying text messages
*/
if(!com) var com={};
if(!com.ksla) com.ksla={};
com.ksla.iframe = function(){
// initiate variable from libs
var dumpd = com.ksla.libs.dumpd;
var dumpi = com.ksla.libs.dumpi;
var dumpw = com.ksla.libs.dumpw;
var dumpe = com.ksla.libs.dumpe;
var trim = com.ksla.libs.trim;
/**
* window instance
* @type Window
*/
var w;
var selectedWord;
var http_request = null;
/**
* Message to show
* @type
*/
var msg;
var response;
var iframe;
var xPointOfNote, yPointOfNote, widthOfNote, heightOfNote;
var extFolder = null;
var dictCheckTMPfile = null;
const DICTCHECK_TMP_FILENAME = "tmp2.html";
const WIND_TO_BE_OPENED='chrome://dictcheck/content/iframeInfoDialog.xul';
const WIND_ID='myIFrameInfoDialogWindow';
const WIND_NAME='my_iframe_info_dialog';
const CONTENT_AREA_ID='myIFrameArea';
const WORD_SEARCH_AREA_ID='wordSearchArea';
const WINDOW_WIDTH = 300;
const WINDOW_HEIGHT = 300;
const MIN_WINDOW_WIDTH = 170;
const MIN_WINDOW_HEIGHT = 80;
const URL_ADDRESS = 'http://www.angool.com/search/index.php?query=';
const iframeBody_csslink = "<link rel='stylesheet' type='text/css' href='chrome://dictcheck/skin/iframeBody.css'/>";
const iframeBody_footer1 = "<span id='footer1'><p><center>Translated with <b>Angool.com</b></center></span>";
const iframeBody_footer2 = "<span id='footer2'><center>dictCheck made by ksla</center><p></span>";
//const iframeBody_footer2 = "<span id='footer2'><center><a href='http://ksla.cba.pl' >dictCheck made by <b>ksla</b></a></center><p></span>";
//onclick='com.ksla.libs.runInFirefox(http://ksla.cba.pl)'
const TEST =
'<html> <head> <title>Strona testowa</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body>SDFSADFAF </body> </html>';
const inner_style = '<style type="text/css">\
#footer1, #footer1 a\
{\
font-size: 10px;\
color: red;\
}\
\
#footer1 p\
{\
margin: 0px;\
margin-top: 20px;\
}\
\
#footer2, #footer2 a\
{\
color: blue;\
font-size: 12px ;\
}\
\
#footer2 p\
{\
margin-bottom: 30px;\
}\
</style>';
/**
* function opening my text info dialog
* Once this function is called openedWindow won't be loaded yet
* and getElementsById might not work!
* We must get the handler to window during 'onLoad'
*/
function openMyIFrameInfoDialog(selWord,message,resp){
dumpi('start->openMyIFrameInfoDialog()');
w=window.openDialog
(
WIND_TO_BE_OPENED
,WIND_NAME
,'chrome=yes,dependent=yes,resizable=yes,modal=no,centerscreen'
,selWord,message,resp
);
};
function modifyMyWindow(){
dumpi('start->modifyMyWindow()');
if(w==null){
dumpi('window "w" == null');
}
else {
dumpi('window "w" was initialized as global');
}
// read window arguments
if("arguments" in w && w.arguments.length > 0) {
msg = w.arguments[1];
response = w.arguments[2];
setIFrameContent(msg);
}
w.document.getElementById(WORD_SEARCH_AREA_ID).focus();
// setText('jazda');
dumpi('sssss');
// dumpi('resp_msg='+response);
// listElementsOfDocument(w.document);
w.onload = windowInitUI;
};
/**
* This function works only with the <textbox> so it cannot be used
* for iFrame based dialog window
* @param {} txt
* @return {Boolean}
*/
function setText(txt){
dumpi('start->setText()');
var txtbox = null;
try {
txtbox = w.document.getElementById(CONTENT_AREA_ID);
}
catch (err) {
dumpe('Exception - Error!!!');
}
if (txtbox == null) {
dumpe('textbox id=['+CONTENT_AREA_ID+'] cannot be found in the document!');
return false;
}
txtbox.value=txt;
return true;
};
function myAlertDOMloaded(){
// alert('DOM Content loaded');
// contDoc.body.innerHTML = "";
var contDoc = iframe.contentDocument;
// listElementsOfDocument(contDoc);
var list = contDoc.getElementsByTagName('tr');
dumpi('---Elements of ['+contDoc.nodeName+']');
var a = [];
var re = new RegExp('angool_row*');
for (var i=0; i<list.length;i++){
// dumpi('el='+list[i].tagName+' id='+list[i].id + 'classn=' + list[i].className);
if(re.test(list[i].className)) a.push(list[i]);
}
dumpi('array "a" has '+ a.length +' elements');
// var tempInnerHTML = contDoc.body.innerHTML;
contDoc.body.innerHTML = "";
if(!checkIfWordDefinitionFound(a)){
//makes new request for
if(!proposeAlternateWord()){
// contDoc.body.innerHTML = tempInnerHTML;
contDoc.body.innerHTML += "Brak znalezionych definicji słowa.";
}
return;
}
else {
var newTABLE = contDoc.createElement("table");
for (var i=0; i<a.length; i++){
newTABLE.appendChild(a[i]);
}
contDoc.body.appendChild(newTABLE);
}
// contDoc.body.innerHTML += iframeBody_csslink + iframeBody_footer1 + iframeBody_footer2;
contDoc.body.innerHTML += inner_style + iframeBody_footer1 + iframeBody_footer2;
dumpi("HTMLcontent="+contDoc.body.innerHTML);
// var link = contDoc.createElement("a");
// link.setAttribute("id", "link_ang");
// link.setAttribute("href", "http://angool.com");
// link.textContent = "Translated with Angool.com";
// contDoc.body.appendChild(link);
};
function checkIfWordDefinitionFound(lst){
// dumpi('lst length= '+lst.length);
if(lst.length == 1 && lst[0].childNodes.length != null){
// dumpi('length=='+lst[0].childNodes.length)
var tdlist = lst[0].getElementsByTagName('td');
var data ;
if (tdlist != null) {
// dumpi('td != null');
// dumpi('td length=' + tdlist.length);
dumpi('data==['+tdlist[0].textContent+']');
data = tdlist[0].textContent;
var re = new RegExp('.*Brak znalezionych.*');
if (re.test(data)) {
dumpi('nie ma definicji');
return false;
}
}
}
return true;
}
function proposeAlternateWord(){
dumpi('proposing alternate word');
// dumpi('word=='+word);
// dumpi('selectedWord=='+selectedWord);
dumpi('w.arg[0]='+w.arguments[0]);
if(selectedWord==null){
selectedWord = w.arguments[0];
}
dumpi('selectedWord=='+selectedWord);
var re = null;
re = new RegExp('ies$|ied$');
if(re.test(selectedWord)){
selectedWord = selectedWord.substring(0,selectedWord.length-3);
selectedWord = selectedWord.concat('y');
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
re = new RegExp('lling$|tting$');
if(re.test(selectedWord)){
selectedWord = selectedWord.substring(0,selectedWord.length-4);
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
re = new RegExp('ing$');
if(re.test(selectedWord)){
selectedWord = selectedWord.substring(0,selectedWord.length-3);
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
re = new RegExp('s$');
if(re.test(selectedWord)){
dumpi('word ends with "s"');
selectedWord = selectedWord.substring(0,selectedWord.length-1);
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
re = new RegExp('ed$');
if(re.test(selectedWord)){
selectedWord = selectedWord.substring(0,selectedWord.length-1);
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
re = new RegExp('e$');
if(re.test(selectedWord)){
selectedWord = selectedWord.substring(0,selectedWord.length-1);
dumpi('selectedWord after modif = '+ selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
return false;
}
function getElementsByClassName(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++){
if(re.test(els[i].className))a.push(els[i]);
}
return a;
}
/**
* Fills IFrameContent with resopnse from URL site (which is supposed to be definition of word)
* @param {} txt
* @return {Boolean}
*/
function setIFrameContent(txt){
dumpi('start->setIFrameContent()');
dumpi('txt='+txt);
dumpi('msg='+msg);
// dumpi('response='+response);
iframe = null;
try {
iframe = w.document.getElementById(CONTENT_AREA_ID);
}
catch (err) {
dumpe('Exception - Error!!!');
}
if (iframe == null) {
dumpe('iframe id=['+CONTENT_AREA_ID+'] cannot be found in the document!');
return false;
}
// iframe.src = "http://google.pl";
dumpi('selectedWord='+selectedWord);
try {
if (iframe.addEventListener)
{
//register the onload event handler for the window
// iframe.removeEventListener ("DOMContentLoaded", alert(), true);
iframe.addEventListener ("DOMContentLoaded", myAlertDOMloaded, true);
}
}
catch(ex) {
dumpe('Exception caught when setting eventListener for iframe');
}
dumpi('file path='+dictCheckTMPfile.path);
iframe.setAttribute('src','file:///'+dictCheckTMPfile.path);
var contDoc = iframe.contentDocument;
// contDoc.body.innerHTML = response;
// dumpi('iframe:');
// listElementsOfDocument(iframe);
// cleanHtml();
return true;
}
function cleanHtml(){
dumpi('start->cleanHtml()');
var el1= document.getElementById('dc_2');
if (el1 == null) {
dumpe('el1 == null !!');
}
else {
dumpi('nodeName='+el1.nodeName);
}
}
function myGetElementById(elemId, doc)
{
if (doc == null)
return document.getElementById(elemId);
else
return doc.getElementById(elemId);
}
function windowInitUI()
{
}
function showMyAbout(e){
window.openDialog
(
'chrome://dictcheck/content/aboutMeDialog.xul'
,"AboutMeDialog_name"
,'chrome=yes,dependent=yes,resizable=no,modal=no,centerscreen'
);
}
/**
*
*/
function startResizingMyInfoDialog(e)
{
if (e.button==0)
{
dumpi('button_0->startResizingMyInfoDialog');
xPointOfNote = e.screenX;
widthOfNote = w.document.width;
yPointOfNote = e.screenY;
heightOfNote = w.document.height;
//~ dumpd(" xPointOfNote="+xPointOfNote+" ; yPointOfNote="+yPointOfNote);
w.addEventListener("mousemove", resizeNote, true);
w.addEventListener("mouseup", stopResizingNote, true);
}
}
/**
*
*/
function stopResizingNote(e)
{
w.removeEventListener("mousemove", resizeNote, true);
w.removeEventListener("mouseup", stopResizingNote, true);
w.document.getElementById(WORD_SEARCH_AREA_ID).focus();
}
/**
*
*/
function resizeNote(e)
{
// dumpd(" w.document.width="+window.document.width+" ; w.document.height="+window.document.height);
var newWidth = widthOfNote + e.screenX - xPointOfNote;
var newHeight = heightOfNote + e.screenY - yPointOfNote;
newWidth = newWidth<MIN_WINDOW_WIDTH ? MIN_WINDOW_WIDTH : newWidth;
newHeight = newHeight<MIN_WINDOW_HEIGHT ? MIN_WINDOW_HEIGHT : newHeight;
w.resizeTo(newWidth,newHeight);
}
/**
* This method is executed immediately after user double clicks on word.
* It starts makeDCRequest(..)
*/
function getSelectedTextAndOpenWindow(e){
//get the selected string from the active window
var focusedWindow = new XPCNativeWrapper(document.commandDispatcher.focusedWindow, 'document', 'getSelection()');
selectedWord = focusedWindow.getSelection().toString();
selectedWord = (trim(selectedWord)).toLowerCase();
if(selectedWord == ""){
return;
}
selectedWord = com.ksla.libs.escapeToLatin1(selectedWord);
dumpi('word trimmed:'+trim(selectedWord));
//Executing the asynchronous request
makeDCRequest(URL_ADDRESS + selectedWord,'');
// openMyTextInfoDialog(selectedWord);
}
function getSelectedTextAndOpenWindowForFF(e){
//get the selected string from the active window
var focusedWindow = new XPCNativeWrapper(document.commandDispatcher.focusedWindow, 'document', 'getSelection()');
selectedWord = focusedWindow.getSelection().toString();
selectedWord = (trim(selectedWord)).toLowerCase();
if(selectedWord == ""){
return;
}
selectedWord = com.ksla.libs.escapeToLatin1(selectedWord);
// dumpi('trimmed:'+trim(selectedWord));
makeDCRequest(URL_ADDRESS + selectedWord,'');
// openMyTextInfoDialog(selectedWord);
}
function searchForNewWord(e){
var word_search_area = w.document.getElementById(WORD_SEARCH_AREA_ID);
selectedWord = trim(word_search_area.value);
selectedWord = com.ksla.libs.escapeToLatin1(selectedWord);
// alert(selectedWord);
// dumpi('selected word from search bar: ' + selectedWord);
makeDCRequest(URL_ADDRESS + selectedWord,'');
return true
}
/**
* Makes the request to URL site and opens and calls 'responseDCHandler' which opens a window
* @param {} url
* @param {} parameters
* @return {Boolean}
*/
function makeDCRequest(url, parameters) {
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml; charset=iso-8859-2');
}
if (!http_request) {
//alert('DictCheck: Cannot create XMLHTTP instance');
dumpe('DictCheck: Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = responseDCHandler;
http_request.open('GET', url + parameters, true);
// http_request.setRequestHeader("Accept-Language", "pl");
// http_request.setRequestHeader("Accept-Charset", "iso-8859-1");
http_request.send(null);
dumpi("makeDCRequest");
return true;
}
function filterAngoolPage(temp){
temp = temp.replace(/\r\n|\n|\r/g,'');
// temp = temp.replace(/\n/g,'');
// temp = temp.replace(/\/>/g,'\n');
temp = temp.replace(/<! --/g,'<!--');
temp = temp.replace(/--->>/g,'');
// temp = temp.replace(/<!--.*-->/g,'');
// initTemporaryFile(DICTCHECK_TMP_FILENAME);
// writeToTemporaryFile(temp);
temp = temp.replace(/<\/*link.*?>/g,'');
// temp = temp.replace(/<META.*?>/g,'');
// temp = temp.replace(/<meta.*?>/g,'');
// temp = temp.replace(/<script.*?>/g,'');
temp = temp.replace(/<script.*?<\/script>/g,'');
temp = temp.replace(/<\/*script.*?>/g,'');
temp = temp.replace(/<a.*?<\/a>/g,'');
// temp = temp.replace(/href=["|'].*?["|']/g,'href=""');
// temp = temp.replace(/src=["|'].*?["|']/g,'src=""');
temp = temp.replace(/alt=["|'].*?["|']/g,'src=""');
temp = temp.replace(/<\/*img.*?>/g,'');
// temp = temp.replace(/<body leftmargin="0".*?>/g,'<body leftmargin="20" width="90%" align="center">');
// temp = temp.replace(/<table width="100%"/g,'<table width="85%"');
temp = temp.replace(/>/g,'>\n');
return temp;
}
function responseDCHandler(){
if (http_request==null){
//alert('http_request==null !!');
dumpe('http_request==null !!');
}
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//var msg = http_request.getResponseHeader();
var msg_header = http_request.getAllResponseHeaders();
var xmlobject = http_request.responseXML;
// if(xmlobject.documentElement.tagName == "parsererror"){
// var parseErrorText = xmlobject.documentElement.firstChild.data;
// parseErrorText += "\n" + xmlobject.documentElement.firstChild.nextSibling.firstChild.data;
// alert(parseErrorText);
// }
var body = xmlobject.body ;
if (body==null) dumpi('body == null');
var tabs = xmlobject.getElementsByTagName('*');
// var tables = xmlobject.getElementsByTagName('table');
dumpi('listing [' + tabs.length + '] tables..');
for (var i=0; i<tabs.length;i++){
dumpi('obj='+tabs[i].tagName);
}
dumpi('..end of listing');
var respText = http_request.responseText;
var temp = respText;
initTemporaryFile("tmp.html");
writeToTemporaryFile(temp);
temp = filterAngoolPage(temp);
initTemporaryFile("tmp2.html");
writeToTemporaryFile(temp);
// var nodeList = xmlobject.childNodes;
// var contType = xmlobject.contentType;
dumpd('responseDCHandler()');
msg = selectedWord + '\n-------\n';
msg = msg+'---HEADER---\n'
+msg_header
+'\n---';
msg = msg+'\n---RESP_TEXT---\n'
+respText
+'\n---';
// dumpd(msg);
openMyIFrameInfoDialog(selectedWord,'',msg) ;
// openMyIFrameInfoDialog(selectedWord, respText) ;
} else {
//alert('There was a problem with the request.');
dumpe('There was a problem with the request.');
}
}
}
function initDirectoryForSaving()
{
var ok = false;
try
{
extFolder = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
extFolder.append("dictCheck");
if( !extFolder.exists() || !extFolder.isDirectory() ) { // if it doesn't exist, create
extFolder.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
}
ok = true;
}
catch (ex)
{
//alert(ex);
dumpe(ex);
}
return ok;
}
function initTemporaryFile(fileName){
// dictCheckTMPfile = Components.classes["@mozilla.org/file/local;1"]
// .createInstance(Components.interfaces.nsILocalFile);
// dictCheckTMPfile.initWithPath(extFolder.path+"//.tmp");
dumpi('initTemporaryFile('+fileName+')');
if (dictCheckTMPfile == null){
// dumpi('dictCheckTMPfile == null');
if(extFolder == null){
// dumpi('extFolder == null');
if(!initDirectoryForSaving()){
dumpe('ExtFolder was not initialized!');
}
}
}
dictCheckTMPfile = extFolder.clone();
dictCheckTMPfile.append(fileName);
if (dictCheckTMPfile.exists()){
// dictCheckTMPfile.remove(true);
dumpi('file ['+fileName+'] already exists!');
}
else {
dictCheckTMPfile.create(dictCheckTMPfile.NORMAL_FILE_TYPE, 0600);
}
dumpi('dictCheckTMPfile='+dictCheckTMPfile.path);
}
function writeToTemporaryFile(txt){
// First, get and initialize the converter
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "iso-8859-2";//"UTF-8"; //TODO to set it as parameter to function
txt = converter.ConvertFromUnicode(txt);
var stream = Components.classes['@mozilla.org/network/file-output-stream;1']
.createInstance(Components.interfaces.nsIFileOutputStream);
//PR_RDONLY 0x01 Open for reading only.
//PR_WRONLY 0x02 Open for writing only.
//PR_RDWR 0x04 Open for reading and writing.
//PR_CREATE_FILE 0x08 If the file does not exist, the file is created. If the file exists, this flag has no effect.
//PR_APPEND 0x10 The file pointer is set to the end of the file prior to each write.
//PR_TRUNCATE 0x20 If the file exists, its length is truncated to 0.
//PR_SYNC 0x40 If set, each write will wait for both the file data and file status to be physically updated.
//PR_EXCL 0x80 With PR_CREATE_FILE, if the file does not exist, the file is created. If the file already exists, no action and NULL is returned.
stream.init(dictCheckTMPfile, 0x02 | 0x08 | 0x20, 0666, false);
stream.write(txt,txt.length);
stream.close();
}
function setGlobals(){
dumpi('start->setGlobals()');
getHandleForDialogWindow();
initDirectoryForSaving();
initTemporaryFile(DICTCHECK_TMP_FILENAME);
}
function getHandleForDialogWindow(){
// dumpi('1');
var windowsMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
// dumpi('2');
// win = windowsMediator.getMostRecentWindow('');
var win_enum = windowsMediator.getEnumerator(null);
var win = null ;
while(win_enum.hasMoreElements()){
dumpi('in the loop');
win = win_enum.getNext();
// dumpi('enum, id='+win.id);
// dumpi('enum, name='+win.name);
if (win.name==WIND_NAME){
w = win;
break;
}
}
return w;
}
function setWindowListeners(){
if (!w) {
dumpe('w is not available');
return false;
}
return true;
}
function listElementsOfDocument(doc){
if (doc==null){
dumpe('Listing Elements: Doc == null!');
return false;
}
if (!(doc instanceof Document)){
dumpw('Listing Elements: Doc is not of type "Document"!');
return false;
}
var list = doc.getElementsByTagName('*');
dumpi('---Elements of ['+doc.nodeName+']');
for (var i=0; i<list.length;i++){
dumpi('el='+list[i].tagName+' id='+list[i].id);
}
dumpi('---');
return true;
}
function onLoad(){
dumpi('window opener href: '+window.opener.location.href);
setGlobals();
modifyMyWindow();
setWindowListeners();
}
///****************************
// public memebers and methods
///****************************
return {
// variables
w:w,
selectedWord:selectedWord,
http_request:http_request,
//functions
setGlobals:setGlobals,
modifyMyWindow:modifyMyWindow,
setWindowListeners:setWindowListeners,
getSelectedTextAndOpenWindow:getSelectedTextAndOpenWindow,
getSelectedTextAndOpenWindowForFF:getSelectedTextAndOpenWindowForFF,
showMyAbout:showMyAbout,
searchForNewWord:searchForNewWord,
startResizingMyInfoDialog:startResizingMyInfoDialog,
onLoad:onLoad
}
//-----------------------------
///****************************
// end of com.ksla.iframe
///****************************
}();
//addEventListener("load", onLoad, true);